<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="rolesList"
        border
        stripe>
          <el-table-column type="expand">
            <template slot-scope="scoped">
              <el-row :class="['bottom',i1 === 0 ? 'top' : '','vcenter']"
                      v-for="(item1, i1) in scoped.row.children"
                      :key="item1.id">
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag
                    closable @close="handleClose(scoped.row, item1.id)">{{ item1.authName }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <!-- 通过for循环嵌套渲染二级权限 -->
                  <el-row :class="[i2 === 0 ? '' : 'top','vcenter']"
                          v-for="(item2, i2) in item1.children" :key="item2.id">
                    <el-col :span="6">
                      <el-tag type="success"
                              closable @close="handleClose(scoped.row, item2.id)">{{ item2.authName }}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag type="warning"
                              v-for="item3 in item2.children"
                              :key="item3.id"
                              closable @close="handleClose(scoped.row, item3.id)">
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" sortable></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" sortable></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scoped">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getRoleById(scoped.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scoped.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="openPower(scoped.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹窗 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="30%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色弹窗 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="30%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px" >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限分配弹窗 -->
    <el-dialog
      title="权限分配"
      :visible.sync="powerDialogVisible"
      width="50%" @close="powerDialogClosed">
      <el-tree
        :data="powerList"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedKeys"
        :props="defaultProps"
        default-expand-all
        ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="powerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPower()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      roleId: '',
      rolesList: [],
      powerList: [],
      checkedKeys: [],
      addDialogVisible: false,
      editDialogVisible: false,
      powerDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        roleName: '',
        roleDesc: '',
        roleId: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 4, max: 10, message: '角色名称在4到10个字符之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色秒速', trigger: 'blur' },
          { min: 4, max: 10, message: '角色描述在4到10个字符之间', trigger: 'blur' }
        ]
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 4, max: 10, message: '角色名称在4到10个字符之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色秒速', trigger: 'blur' },
          { min: 4, max: 10, message: '角色描述在4到10个字符之间', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  methods: {
    // 获取角色列表数据
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status === 200) {
        this.rolesList = res.data
      } else {
        this.$message.error('加载角色列表失败!')
      }
    },
    // 关闭新增角色弹窗
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭修改角色弹窗
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 保存角色
    addRoles () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('新增角色失败!')
        } else {
          this.$message.success('新增角色成功!')
          // 关闭弹窗
          this.addDialogVisible = false
          // 加载列表
          await this.getRolesList()
        }
      })
    },
    // 修改角色
    editRoles () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, this.editForm)
        if (res.meta.status !== 200) {
          this.$message.error('修改角色信息失败!')
        } else {
          this.$message.success('修改角色信息成功!')
          this.editDialogVisible = false
          await this.getRolesList()
        }
      })
    },
    // 通过id查询对应的角色信息
    async getRoleById (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('获取角色信息失败!')
      } else {
        this.editForm = res.data
        this.editDialogVisible = true
      }
    },
    // 删除角色
    deleteRoles (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新列表
          await this.getRolesList()
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async handleClose (row, id) {
      console.log(row)
      const confirmResult = await this.$confirm('是否删除当前标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败!')
      }
      this.$message.success('删除权限成功!')
      // await this.getRolesList()
      row.children = res.data
    },
    // 保存权限分配弹窗
    async editPower () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const str = keys.join(',')
      // 调用接口
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: str })
      if (res.meta.status !== 200) return this.$message.error('权限分配失败!')
      this.$message.success('权限分配成功!')
      await this.getRolesList()
      this.powerDialogVisible = false
    },
    // 权限分配弹窗关闭
    powerDialogClosed () {
      this.checkedKeys = []
    },
    // 打开分配权限弹窗
    async openPower (row) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('加载权限数据失败!')
      }
      this.getPowerKeys(row, this.checkedKeys)
      this.roleId = row.id
      this.powerList = res.data
      this.powerDialogVisible = true
    },
    // 通过递归，获取所有三级权限的id，保存到数组
    getPowerKeys (node, arr) {
      // 三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getPowerKeys(item, arr)
      })
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }
  .top {
   border-top: 1px solid #eee;
  }
  .bottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
